import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_fancy_tree_view/flutter_fancy_tree_view.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/entities/collection_tools_page_entity.dart';
import 'package:flutter_rtk/entities/current_project_entity.dart';
import 'package:flutter_rtk/entities/project_entity.dart';
import 'package:flutter_rtk/entities/tools_entity.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class ProjectSwitchPage extends StatefulWidget {
  const ProjectSwitchPage({super.key});

  @override
  State<ProjectSwitchPage> createState() => _ProjectSwitchPageState();
}

class _ProjectSwitchPageState extends State<ProjectSwitchPage> {
  late TextEditingController _textEditingController;
  late FocusNode focusNode;
  bool _hasFocus = false;

  //
  late TreeViewController _treeController;
  late ScrollController _scrollController;

  _buildMainView() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: mainAppBar(title: "我的项目"),
      body: Column(children: [
        Container(width: double.infinity, height: 20.h, color: const Color(0xFFF4F4F4)),
        _buildSearchInput(),
        Expanded(child: _buildTreeView()),
      ]),
    );
  }

  _buildSearchInput() {
    return Container(
      width: double.infinity,
      height: 70.h,
      margin: EdgeInsets.symmetric(horizontal: 30.w, vertical: 20.h),
      child: TextField(
        controller: _textEditingController,
        focusNode: focusNode,
        decoration: InputDecoration(
          hintText: "请输入",
          hintStyle: TextStyle(fontSize: 24.sp, color: const Color(0xFFBBBBBB)),
          prefixIcon: SizedBox(width: 50.w, height: 50.w, child: Center(child: ImageIcon(const AssetImage(AppAssets.projectSearchIcon), size: 28.w, color: _hasFocus ? AppConstants.brandColor : const Color(0xFFBBBBBB)))),
          prefixIconConstraints: BoxConstraints.loose(Size(50.w, 50.w)),
          suffixIcon: SizedBox(
            width: 154.w,
            height: double.infinity,
            child: Row(children: [
              _hasFocus
                  ? SizedBox(
                      width: 32.w,
                      height: 32.w,
                      child: IconButton(
                        onPressed: () {
                          SchedulerBinding.instance.addPostFrameCallback((_) {
                            _textEditingController.clear();
                            var projects = context.read<AppModel>().projects;
                            final rootNode = TreeNode(id: "Root");
                            _buildTreeNode(projects, rootNode);
                            _treeController = TreeViewController(rootNode: rootNode)..expandAll();
                            setState(() {});
                          });
                        },
                        icon: Image.asset(AppAssets.projectClearIcon),
                        padding: EdgeInsets.zero,
                      ),
                    )
                  : SizedBox(width: 32.w),
              SizedBox(width: 10.w),
              Expanded(child: _buildSearchBtn()),
              SizedBox(width: 10.w),
            ]),
          ),
          suffixIconConstraints: BoxConstraints.loose(Size(185.w, 70.h)),
          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(70.r), borderSide: BorderSide(color: const Color(0xFFE1E1E1), width: 1.w)),
          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(70.r), borderSide: BorderSide(color: AppConstants.brandColor, width: 1.w)),
          isCollapsed: true,
        ),
        onEditingComplete: _doSearch,
        textAlignVertical: TextAlignVertical.center,
        autocorrect: false,
        contextMenuBuilder: (context, state) => const SizedBox.shrink(),
      ),
    );
  }

  _buildSearchBtn() {
    return Container(
      width: 125.w,
      height: 60.h,
      padding: EdgeInsets.symmetric(vertical: 5.h),
      alignment: Alignment.center,
      child: TextButton(
        style: ButtonStyle(
          splashFactory: NoSplash.splashFactory,
          backgroundColor: MaterialStateProperty.all(const Color(0xFFEAF3FF)),
          shape: MaterialStateProperty.all(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(90.r)),
          ),
          padding: MaterialStateProperty.all(EdgeInsets.zero),
          elevation: MaterialStateProperty.all(0),
        ),
        onPressed: _doSearch,
        child: Text("搜索", style: TextStyle(fontSize: 28.sp, color: _hasFocus ? const Color(0xFF0070FF) : const Color(0xFFBBBBBB), fontWeight: FontWeight.w700)),
      ),
    );
  }

  _doSearch() {
    var s = _textEditingController.value.text;
    if (s.isEmpty) {
      return;
    }
    var projects = context.read<AppModel>().projects;
    List<ProjectEntity> projects0 = [];
    for (var value in projects) {
      projects0.add(value.copyWith());
    }
    final rootNode = TreeNode(id: "Root");
    _buildTreeNode(_filterProjects(projects0, s), rootNode);
    _treeController = TreeViewController(rootNode: rootNode)..expandAll();
    setState(() {});
  }

  _filterProjects(List<ProjectEntity> projects, String kw) {
    List<ProjectEntity> targets = [];
    for (ProjectEntity p in projects) {
      if (p.mergeName.contains(kw)) {
        if (p.children.isNotEmpty) {
          List<ProjectEntity> children = _filterProjects(p.children.map((e) => ProjectEntity.fromJson(e)).toList(), kw);
          if (children.isNotEmpty) {
            p.children = children;
          }
        }
        targets.add(p);
      } else {
        List<ProjectEntity> children = _filterProjects(p.children.map((e) => ProjectEntity.fromJson(e)).toList(), kw);
        if (children.isNotEmpty) {
          p.children = children;
          targets.add(p);
        }
      }
    }
    return targets;
  }

  _buildTreeView() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 30.w),
      child: Scrollbar(
        thumbVisibility: false,
        controller: _scrollController,
        child: TreeView(
          controller: _treeController,
          scrollController: _scrollController,
          nodeHeight: 90.h,
          theme: const TreeViewTheme(),
          nodeBuilder: (_, entry) {
            return InkWell(
              onTap: () async {
                if (entry.hasChildren) {
                  _treeController.toggleExpanded(entry);
                } else {
                  EasyLoading.show(status: "项目切换中");
                  //  选中, 获取数据, 返回
                  ProjectEntity project = entry.data as ProjectEntity;
                  context.read<AppModel>().setCurrentProject(CurrentProjectEntity(project.projectId, "--", project.deptName, "--", "--", "--", 0, 0, "", project.projectCode, project.projectId, project.deptCode, "", project.mergeName));
                  try {
                    // 常用工具
                    CollectionToolsPageEntity collectionToolsPageEntity = await AppApi.getCommonTools(projectId: project.projectId, projectCode: project.projectCode);
                    context.read<AppModel>().setCollectionTools(collectionToolsPageEntity);
                    // 所有工具
                    List<ToolsEntity> tools = await AppApi.getAllTools(projectId: project.projectId, projectCode: project.projectCode);
                    context.read<AppModel>().setAllTools(tools);
                  } catch (e, stack) {
                    debugPrintStack(stackTrace: stack);
                  }
                  EasyLoading.dismiss();
                  Navigator.pop(context);
                }
              },
              child: SizedBox(
                width: double.infinity,
                height: 90.h,
                child: Column(children: [
                  Expanded(child: _buildTreeItem(entry)),
                  Divider(color: const Color(0xFFE7E7E7), height: 1.h),
                ]),
              ),
            );
          },
        ),
      ),
    );
  }

  _buildTreeItem(TreeNode entry) {
    // 行构建
    // 层级间距, 三角形箭头, 图标间距, 图标, 内容间距, 内容
    List<Widget> widgets = [];
    // 层级间距
    widgets.add(SizedBox(width: 15.w * entry.depth));
    // 三角形箭头
    if (entry.hasChildren) {
      if (_treeController.isExpanded(entry.id)) {
        widgets.add(SizedBox(width: 15.w, height: 15.w, child: Image.asset(AppAssets.projectDownArrowIcon)));
      } else {
        widgets.add(SizedBox(width: 15.w, height: 15.w, child: Image.asset(AppAssets.projectRightArrowIcon)));
      }
    }
    // 图标间距
    widgets.add(SizedBox(width: 15.w));
    // 图标
    if (entry.hasChildren) {
      if (entry.depth == 0) {
        // 跟目录图标
        widgets.add(SizedBox(width: 24.w, height: 24.w, child: Image.asset(AppAssets.projectTreeIcon)));
      } else {
        // 非更目录图标
        widgets.add(SizedBox(width: 24.w, height: 24.w, child: Image.asset(AppAssets.projectFolderIcon)));
      }
    } else {
      widgets.add(SizedBox(width: 15.w));
      widgets.add(Container(width: 13.w, height: 13.w, decoration: BoxDecoration(borderRadius: BorderRadius.circular(13.r), color: const Color(0xFFD5D5D5))));
    }
    // 内容间距
    widgets.add(SizedBox(width: 15.w));
    widgets.add(Expanded(child: Text(entry.label, overflow: TextOverflow.ellipsis)));
    return Row(children: widgets);
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    focusNode = FocusNode()
      ..addListener(() {
        setState(() {
          _hasFocus = focusNode.hasFocus;
        });
      });
    _scrollController = ScrollController()
      ..addListener(() {
        focusNode.unfocus();
      });
    var projects = context.read<AppModel>().projects;
    final rootNode = TreeNode(id: "Root");
    _buildTreeNode(projects, rootNode);
    _treeController = TreeViewController(rootNode: rootNode)..expandAll();
  }

  _buildTreeNode(List<ProjectEntity> projects, TreeNode parentNode) {
    for (ProjectEntity p in projects) {
      var treeNode = TreeNode(id: p.mergeName, label: p.mergeName, data: p);
      if (p.children.isNotEmpty) {
        _buildTreeNode(
            p.children.map((e) {
              if (e is ProjectEntity) {
                return e;
              }
              return ProjectEntity.fromJson(e);
            }).toList(),
            treeNode);
      }
      parentNode.addChild(treeNode);
    }
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _treeController.dispose();
    _scrollController.dispose();
    focusNode.dispose();
    super.dispose();
  }
}
